﻿using System;
using System.Data;
using System.Data.Entity;
using System.Data.Objects;
using Super.Entities;

namespace Super.Infrastructure
{
    public class DbContextAdapter : IObjectSetFactory, IObjectContext
    {
        private readonly ObjectContext _context;
        public string ErrorMessage = null;

        public DbContextAdapter()
        {
            _context = new SuperEntities();
            //_context.ContextOptions.LazyLoadingEnabled = false;
        }

        public DbContextAdapter(bool isLazy)
        {
            _context = new SuperEntities();
            _context.ContextOptions.LazyLoadingEnabled = isLazy;
            
        }

        #region IObjectContext Members

        public void SaveChanges()
        {
            try
            {
                _context.SaveChanges();
            }
            catch (Exception ex)
            {
               ErrorMessage = ex.Message;
               while (ex.InnerException!=null)
                {
                    ErrorMessage += ex.InnerException.Message;
                    ex = ex.InnerException;
                }
                
            }

        }

        #endregion

        #region IObjectSetFactory Members

        /// <summary>
        /// dispose时自动批量保存
        /// </summary>
        public void Dispose()
        {
             SaveChanges();
            _context.Dispose();
        }

        /// <summary>
        /// 创建实体集
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public IObjectSet<T> CreateObjectSet<T>() where T : class
        {
            return _context.CreateObjectSet<T>();
        }

        public ObjectContext CreateObjectContext()
        {
            return _context;
        }

        /// <summary>
        /// 更改实体状态
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="state"></param>
        public void ChangeObjectState(object entity, EntityState state)
        {
            _context.ObjectStateManager.ChangeObjectState(entity, state);
       
        }

        /// <summary>
        /// 属性实体 //通过触发器添加的字段没有跟新上来
        /// </summary>
        /// <param name="entity"></param>
        public void Refresh(object entity)
        {
            _context.Refresh(RefreshMode.StoreWins,entity);
        }

        #endregion
    }
}
